<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\View;
use think\facade\Cache;
use app\addons\File;
use app\admin\BaseController;
use app\admin\model\Catalog;
use app\admin\model\Config;
/**
 * 语言管理
 */
class Lang extends BaseController
{
    protected function initialize()
    {
        parent::initialize();
        $this->path    = public_path() . 'lang/';
        $this->default = include($this->path . $this->request->langDefault . '.php');
        $this->list    = unserialize(config('app.language'));
        foreach ($this->list as $key => $val) {
            // 参数读取
            $filename  = $this->path . $val['name'] . '.php'; 
            $parameter = is_file($filename) ? include($filename) : [];
            $this->list[$key]['parameter'] = [];
            foreach ($this->default as $k => $v) {
                $arr['title'] = $k;
                $arr['value'] = isset($parameter[$k]) ? $parameter[$k] : "";
                array_push($this->list[$key]['parameter'], $arr);
            }
        }
        $this->list = array_sort($this->list, 'sort');
    }

    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            return json(['status' => 'success', 'message' => '获取成功', 'data' => $this->list]);
        } else {
            return View::fetch();
        }
    }

    /**
     * 保存更新的资源
     */
    public function update()
    {
        try {
            $input = input();
            // 设置默认值
            if ($input['default'] === 1) {
                foreach ($this->list as $key => $value) {
                    $this->list[$key]['default'] = 0;
                }
            }
            // 新增或修改
            if (isset($input['isNews']) && $input['isNews'] === 1) {
                array_push($this->list, $input);
            } else {
                foreach ($this->list as $key => $value) {
                    if ($value['name'] === $input['name']) {
                        $this->list[$key] = $input;
                    }
                }
            }
            $index = [];
            $basics = "";
            // 写入语言参数
            foreach ($this->list as $key => $val) {
                $filename  = $this->path . $val['name'] . '.php';
                $parameter = [];
                foreach ($val['parameter'] as $k => $v) {
                    $parameter[$v['title']] = $v['value'];
                }
                $content = "<?php\nreturn ".var_export($parameter,true).";";
                File::create($filename, $content);
                unset($this->list[$key]['parameter']);
                unset($this->list[$key]['isNews']);
                if ($val['default'] === 1) {
                    $index = Catalog::where('seo_url', 'index')->where('language', $val['name'])->withoutField('id')->find();
                    $basics = Config::where('name', 'basics_' . $val['name'])->value('value');
                }
            }
            // 新语言初始化
            if (isset($input['isNews']) && $input['isNews'] === 1) {
                if ($index) {
                    $index = $index->toArray();
                    $index['pid'] = 0;
                    $index['language'] = $input['name'];
                    $beIndex  = Catalog::where('seo_url', 'index')->where('language', $input['name'])->value('id');
                    if (! $beIndex) {
                        Catalog::create($index);
                    }
                }
                $beBasics = Config::where('name', 'basics_' . $input['name'])->value('value');
                if (! $beBasics) {
                    Config::create(['title' => '基础配置', 'name' => 'basics_' . $input['name'], 'value' => $basics]);
                }
                Cache::clear();
            }
            // 写入配置文件
            $pat[] = 'language';
            $rep[] = serialize($this->list);
            File::editConfig($pat, $rep , config_path().'app.php');
            return json(['status' => 'success', 'message' => '操作成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }
    /**
     * 删除
     */
    public function delete() {
        $input = input();
        $unset = [];
        foreach ($this->list as $key => $val) {
            foreach ($input['rows'] as $k => $v) {
                if ($val['name'] === $v['name']) {
                    unset($this->list[$key]);
                }
            }
            unset($this->list[$key]['parameter']);
        }
        $this->list = array_values($this->list);
        $pat[] = 'language';
        $rep[] = serialize($this->list);
        File::editConfig($pat, $rep , config_path().'app.php');
        return json(['status' => 'success', 'message' => '操作成功']);
    }
    /**
     * 排序
     */
    public function sort() {
        $input = input();
        $unset = [];
        $list  = $input['list'];
        $count = count($input['list']);
        foreach ($list as $key => $value) {
            $list[$key]['sort'] = $count - $key;
            unset($list[$key]['parameter']);
        }
        $pat[] = 'language';
        $rep[] = serialize($list);
        File::editConfig($pat, $rep , config_path().'app.php');
        return json(['status' => 'success', 'message' => '操作成功']);
    }
}